/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 单号限额modal组件
 *  */
import React, { useState, useEffect, useCallback } from "react"
import { Modal, Form, Radio, Row, Col, Select, InputNumber } from 'antd'
import { connect } from 'dva'
const FormItem = Form.Item
const RadioGroup = Radio.Group;
const Option = Select.Option;

let ModalLimit = (props) => {
  const {
    form: { getFieldDecorator, validateFields , resetFields },
    visible,
    close,
    dispatch,
    getList,
    record: { allowance_count, id }
  } = props
  const radioStyle = {
    display: "block",
    height: "30px",
    lineHeight: "30px"
  };
  let num = allowance_count
  const [radio, setRadio] = useState(1)
  const [iniRadio, setIniRadio] = useState(0)
  const [restNum, setRestNum] = useState(null)
  const [selectValue, setSelectValue] = useState("increase")
  const [count, setCount] = useState(null)
  const [help, setHelp] = useState('')

  useEffect(() => {
    if (num < 0) {
      setRadio(1) 
      setIniRadio(1)
      setRestNum(null)
    } else {
      setRadio(2)
      setIniRadio(2)
      setRestNum(num)
    }
  }, [num, visible])

  const checkInput = useCallback((rule, value, callback) => {
    let reg = /^\d+$/;
    if (radio == 2) { //有限单号
      if (value == "") {
        setHelp("请填写追加或减少的数量")
        callback("error");
      } else if (!reg.test(value)) {
        setHelp("请输入正确的数量")
        callback("error");
      } else if (selectValue == "reduce") {
        if (value > restNum*1) {
          setHelp("减少的单量不可大于剩余单量")
          callback("error");
        } else {
          setHelp("")
          callback();
        }
      } else if (value + restNum*1 > 9999) {
        setHelp("总单量不能超过9999")
        callback("error");
      } else {
        setHelp("")
        callback();
      }
    } else {
      setHelp("")
      callback();
    }
  }, [count, radio, help, selectValue])

  const handleSelect = useCallback((val) => {
    resetFields()
    setHelp("")
    setSelectValue(val)
  }, [])

  const handleRadioChange = useCallback((val) => {
    setRadio(val)
    resetFields();  //重置表单数据，使校验数据函数可以再次调用
    setHelp("")
  }, [radio])

  const handleClose = useCallback(bool => {
    close(bool)
    setHelp("")
    setCount(null)
    setSelectValue("increase")
    setRadio(iniRadio)
  }, [visible])

  const handleInputChange = useCallback(
    (val) => {
      setCount(val)
      setRadio(2)
    },
    [count]
  )

  const handleOk = useCallback(() => {
    validateFields((err, fieldValue) => {
      if (err) return
      let total
      if( selectValue == "increase" ){
        total = Number(restNum) + count
      }else{
        total = Number(restNum) - count
      }
      let payload = {
        id,
        num: total
      }
      if (radio === 1) {
        payload.num = -1
      }

      delete payload.select
      dispatch({
        type: "orderNumSet/setNumber",
        payload
      }).then(res=>{
        getList()
      });
      handleClose()
    })
  }, [count, selectValue, radio])

  return (
    <Modal
      destroyOnClose
      title='剩余单量'
      visible={visible}
      onCancel={() => handleClose(false)}
      okText='确认'
      cancelText='取消'
      centered
      onOk={() => handleOk()}
    >
      <Form>
        <RadioGroup name="radiogroup" value={radio} onChange={e => handleRadioChange(e.target.value)}>
          <FormItem>
            <Radio style={radioStyle} value={1}>不限单量</Radio>
            <p style={{ marginLeft: "24px" }}>
              选择不限单量，则快递员打印快宝同城面单没有限额，可无限打印
            </p>
          </FormItem>
          <div>
            <Radio style={radioStyle} value={2}>
              有限单量
              {restNum ? <span style={{ marginLeft: "100px" }}>剩余单量：{restNum}</span> : null}
            </Radio>
            <Row>
              {
                restNum ? <Col span={9}>
                  <FormItem>
                    {
                      getFieldDecorator("select", {
                        initialValue: selectValue
                      })(
                        <Select placeholder='追加' style={{ width: 120 }} onChange={(val) => handleSelect(val)}>
                          <Option value="increase">追加</Option>
                          <Option value="reduce">减少</Option>
                        </Select>
                      )
                    }
                  </FormItem>
                </Col> : null
              }
              <Col span={15}>
                <FormItem help={help}>
                  {getFieldDecorator("num", {
                    initialValue: count,
                    rules: [
                      {
                        validator: checkInput
                      }
                    ]
                  })(
                    <InputNumber
                      min={1}
                      max={9999}
                      step={10}
                      placeholder="请填写追加或减少的数量"
                      style={{ width: "210px" }}
                      onChange={(val) => handleInputChange(val)}
                    />
                  )}
                </FormItem>
              </Col>
            </Row>
          </div>
          <p>选择有限单量，则快递员打印快宝同城单号存在限额，限额的数量为以上方框填写或显示的剩余单号数量，剩余数量可修改减少或者增加，快递员每打印一单剩余数量-1</p>
        </RadioGroup>
      </Form>
    </Modal>
  )
}
export default Form.create()(
  connect(({ loading }) => ({
    loading
  }))(ModalLimit)
)